// test_vector_store_with_env.js - 带环境变量加载的向量存储功能测试
const dotenv = require('dotenv');
const path = require('path');
const fs = require('fs');

// 加载环境变量
dotenv.config({ path: path.resolve(__dirname, '.env') });

console.log("开始测试向量存储功能...");
console.log("DEEPSEEK_API_KEY:", process.env.DEEPSEEK_API_KEY ? "已设置" : "未设置");

// 检查vector_store目录
const vectorStorePath = path.join(__dirname, 'vector_store');
console.log(`向量存储路径: ${vectorStorePath}`);

if (!fs.existsSync(vectorStorePath)) {
    console.log("创建向量存储目录...");
    fs.mkdirSync(vectorStorePath, { recursive: true });
}

// 测试数据
const testKnowledgePoint = {
    _id: "test_id_1",
    content: "这是一个测试知识点，用于验证向量存储功能是否正常工作。"
};

async function testVectorStore() {
    try {
        // 导入向量存储服务
        const vectorStoreService = require('./services/vectorStoreService');
        console.log("✓ 向量存储服务导入成功");
        
        // 测试添加知识点到向量库
        console.log("正在添加测试知识点到向量库...");
        await vectorStoreService.addKnowledgePointToStore(testKnowledgePoint);
        console.log("✓ 知识点添加成功");
        
        // 检查生成的文件
        const files = fs.readdirSync(vectorStorePath);
        console.log(`向量存储目录中的文件: ${files.join(', ')}`);
        
        // 检查特定文件是否存在
        const indexPath = path.join(vectorStorePath, 'hnswlib.index');
        const argsPath = path.join(vectorStorePath, 'args.json');
        const docStorePath = path.join(vectorStorePath, 'docstore.json');
        
        console.log(`hnswlib.index 存在: ${fs.existsSync(indexPath)}`);
        console.log(`args.json 存在: ${fs.existsSync(argsPath)}`);
        console.log(`docstore.json 存在: ${fs.existsSync(docStorePath)}`);
        
        if (fs.existsSync(indexPath)) {
            const stats = fs.statSync(indexPath);
            console.log(`hnswlib.index 文件大小: ${stats.size} 字节`);
        }
        
        // 测试搜索功能
        console.log("正在测试搜索功能...");
        const results = await vectorStoreService.searchKnowledgePoints("测试知识点");
        console.log(`搜索结果数量: ${results.length}`);
        console.log("✓ 向量存储功能测试完成");
        
    } catch (error) {
        console.error("✗ 向量存储功能测试失败:", error.message);
        console.error("错误堆栈:", error.stack);
    }
}

// 运行测试
testVectorStore();